package com.yonyou.pmclouds.team.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.ChineseStringUtils;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.rmiitf.EnterpriseMaintain;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.entity.TeamToPersonnelVO;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseMaintain;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseQuery;
import com.yonyou.pmclouds.user.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@RestController
@RequestMapping({"/teamEnt", "/outter/teamEnt"})
public class TeamEnterpriseController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterpriseQuery query;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterpriseMaintain maintain;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private EnterpriseMaintain enterpriseMaintain;

    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;

    @Autowired
    private UserInfoQuery userInfoQuery;

    @GetMapping("/count")
    public int countEnterpriseOfProject(@RequestParam("projectid") String projectid) throws BusinessException {
        return query.countProjectEnterprise(projectid);
    }

    @GetMapping("/ents")
    public TeamEnterpriseVO[] getEnterpriseOfProject(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseVO[] result = query.queryByProject(projectid);
        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        if (ArrayUtils.isEmpty(result)) {
            return result;
        }
        Arrays.sort(result, new Comparator<TeamEnterpriseVO>() {
            @Override
            public int compare(TeamEnterpriseVO o1, TeamEnterpriseVO o2) {
                if (o1 == o2) {
                    return 0;
                }
                if (o1 == null) {
                    return 1;
                }
                if (o2 == null) {
                    return -1;
                }
                if (!o1.getEntRole().equals(o2.getEntRole())) {
                    return o1.getEntRole().compareTo(o2.getEntRole());
                }
                return ChineseStringUtils.compareInDict(o1.getEnterpriseName(), o2.getEnterpriseName());
            }
        });
        return result;
    }

    @PostMapping("/add")
    public TeamEnterpriseVO[] addTeamEnterprise(@RequestBody TeamEnterpriseVO[] enterprises, BindingResult result) throws BusinessException {
        if (result.hasErrors()) {
            throw new IllegalRequestArgException();
        }
        String[] added = maintain.addEnterpriseToProject(enterprises[0].getPkProject(), enterprises);
        return query.queryByIds(added);
    }

    @PostMapping("/remove")
    public String removeTeamEnterprise(@RequestBody @Validated TeamEnterpriseVO enterprise, BindingResult result) throws BusinessException {
        if (result.hasErrors()) {
            throw new IllegalRequestArgException();
        }
        return maintain.removeEnterpriseOfTeam(enterprise);
    }

    @RequestMapping("/updateTOPersonnel")
    public String updateTOPersonnel(@RequestParam("pkTenant") String pkTenant) throws BusinessException{
        RuntimeEnvironment.setTenantId(pkTenant);

        List<TeamToPersonnelVO> teamToPersonnelVOS = query.queryEntAndUserByTenant(pkTenant);

        if(teamToPersonnelVOS == null || teamToPersonnelVOS.size() <= 0){
            return "该租户下未查询到项目团队信息，无须升级！";
        }

        List<EnterpriseVO> insertEntList = new ArrayList<>();
        List<String> pkEnterpriseList = new ArrayList<>();
        Set<String> pkUserSet = new HashSet<>();
        for(TeamToPersonnelVO teamToPersonnelVO : teamToPersonnelVOS){

            pkEnterpriseList.add(teamToPersonnelVO.getPkEnterprise());

            EnterpriseVO enterpriseVO = coverTeamTOEnterprise(teamToPersonnelVO, pkTenant);

            PersonnelVO[] personnelVOS = coverTeamToPersonnel(teamToPersonnelVO, pkUserSet);

            enterpriseVO.setPersonnelVOS(personnelVOS);

            insertEntList.add(enterpriseVO);

        }

        setPersonVORelationValue(insertEntList, pkEnterpriseList, pkUserSet);

        enterpriseMaintain.insertEnterprisesByTeam(insertEntList.toArray(new EnterpriseVO[]{}));

        return "项目团队升级完成，共升级企业" + insertEntList.size() + "条";
    }

    private EnterpriseVO coverTeamTOEnterprise(TeamToPersonnelVO teamToPersonnelVO, String pkTenant){
        EnterpriseVO enterpriseVO = new EnterpriseVO();
        String[] entRoles = teamToPersonnelVO.getEntRoles() == null ? new String[]{String.valueOf(TeamEnterpriseVO.EnterpriseRoleConst.ROLE_OWNER)}
                : teamToPersonnelVO.getEntRoles().split(",");
        String[] pkOrgs = teamToPersonnelVO.getPkOrgs() == null ? null : teamToPersonnelVO.getPkOrgs().split(",");
        int pkUserCount = teamToPersonnelVO.getPkUsers() == null ? 0 : teamToPersonnelVO.getPkUsers().split(",").length;

        enterpriseVO.setPkEnterprise(teamToPersonnelVO.getPkEnterprise());
        enterpriseVO.setPkTenant(pkTenant);
        if(pkOrgs != null && pkOrgs.length > 0){
            List<String> pkOrgList = new ArrayList<>();
            for(String pkOrg : pkOrgs){
                if(pkTenant.equalsIgnoreCase(pkOrg) || StringUtils.isEmpty(pkOrg) || "~".equalsIgnoreCase(pkOrg)){
                    continue;
                }
                pkOrgList.add(pkOrg);
                enterpriseVO.setPkOrgs(pkOrgList);
            }
        }
        enterpriseVO.setRole(Byte.parseByte(entRoles[0]));
        enterpriseVO.setPersonnelNum(pkUserCount);
        enterpriseVO.setPlanAuthorizedNum(pkUserCount);
        enterpriseVO.setRealAuthorizedNum(pkUserCount);

        return enterpriseVO;
    }

    private PersonnelVO[] coverTeamToPersonnel(TeamToPersonnelVO teamToPersonnelVO, Set<String> pkUserSet){
        List<PersonnelVO> personnelVOS = new ArrayList<>();
        String pkUsersResult = teamToPersonnelVO.getPkUsers();
        if(StringUtils.isEmpty(pkUsersResult)){
            return new PersonnelVO[0];
        }

        String[] pkUsers = teamToPersonnelVO.getPkUsers().split(",");

        for(String pkUser : pkUsers){
            if(StringUtils.isEmpty(pkUser)){
                continue;
            }

            pkUserSet.add(pkUser);

            PersonnelVO personnelVO = new PersonnelVO();
            personnelVO.setIsSpecialWork((byte) 0);
            personnelVO.setIsContacts((byte) 0);
            personnelVO.setIsYgcAuthorizer((byte) 1);
            personnelVO.setPkEnterprise(teamToPersonnelVO.getPkEnterprise());
            personnelVO.setUserId(pkUser);
            personnelVO.setPkTenant(RuntimeEnvironment.getTenantId());

            personnelVOS.add(personnelVO);

        }

        return personnelVOS.toArray(new PersonnelVO[]{});

    }

    private void setPersonVORelationValue(List<EnterpriseVO> insertEntList, List<String> pkEnterpriseList, Set<String> pkUserSet){
        Map<String, EnterpriseInfo> enterpriseInfoMap = enterpriseInfoQuery.queryEnterpriseByIds(pkEnterpriseList.toArray(new String[]{}));

        UserInfo[] userInfoArray = userInfoQuery.queryUsers(pkUserSet.toArray(new String[]{}));

        Map<String, UserInfo> userInfoMap = new HashMap<>();

        for(UserInfo userInfo : userInfoArray){
            userInfoMap.put(userInfo.getUserId(), userInfo);
        }

        for(EnterpriseVO enterpriseVO : insertEntList){

            // 过滤友互通中未查询到的数据
            List<PersonnelVO> newInsertPersonList = new ArrayList<>();
            EnterpriseInfo enterpriseInfo = enterpriseInfoMap.get(enterpriseVO.getPkEnterprise());

            if(enterpriseInfo != null){
                enterpriseVO.setName(enterpriseInfo.getName());

                PersonnelVO[] personnelVOS = enterpriseVO.getPersonnelVOS();

                for(PersonnelVO personnelVO : personnelVOS){
                    UserInfo userInfo = userInfoMap.get(personnelVO.getUserId());
                    if(userInfo == null || (StringUtils.isEmpty(userInfo.getUserMobile()) && StringUtils.isEmpty(userInfo.getUserEmail()))){
                        continue;
                    }

                    log.debug("项目团队升级到人员登记：企业名称[" + enterpriseVO.getName() + "],用户名称[" + userInfo.getUserName() + "]," +
                            "userId[" + userInfo.getUserId() + "], 手机号[" + userInfo.getUserMobile() + "],用户编码[" + userInfo.getUserCode() + "]");

                    personnelVO.setPhone(userInfo.getUserMobile());
                    personnelVO.setUserName(userInfo.getUserName());
                    personnelVO.setSname(userInfo.getUserName());
                    personnelVO.setEmail(userInfo.getUserEmail());

                    newInsertPersonList.add(personnelVO);
                }

                enterpriseVO.setPersonnelVOS(newInsertPersonList.toArray(new PersonnelVO[]{}));
                int personCount = newInsertPersonList.size();
                enterpriseVO.setPersonnelNum(personCount);
                enterpriseVO.setRealAuthorizedNum(personCount);
                enterpriseVO.setPlanAuthorizedNum(personCount);
            }
        }


    }
}
